package com.da.javatest.thread.other;

import java.util.concurrent.TimeUnit;

/**
 * @author chenlida
 * @date 2020/7/1 17:45
 *
 * sleep方法由于中断而抛出异常之后，线程的中断标志会被清除（置为false），
 * 所以在异常中需要执行this.interrupt()方法，将中断标志位置为true
 */
public class InterruptTest {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread() {
            @Override
            public void run() {
                while (true) {
                    try {
                        TimeUnit.SECONDS.sleep(10);
                    } catch (InterruptedException e) {
                        this.interrupt();
                        e.printStackTrace();
                    }
                    if (this.isInterrupted()) {
                        System.out.println("退出循环");
                        break;
                    }
                }
            }
        };
        thread.setName("thread");
        thread.start();
        TimeUnit.SECONDS.sleep(1);
        thread.interrupt();
    }
}
